import {defineStore} from 'pinia'
import userstore from './userlogin.js'
import {getunlinedata} from '@/api/index.js'
export default defineStore('lt',{
	actions:{
		async ws(){
			const useuserstore=userstore()
			const ws=uni.connectSocket({
				url:"ws://10.27.118.49:3007",
				complete: ()=> {}
			})
		
			this.wss=ws
			ws.onOpen(()=>{
				console.log('ws连接成功！')
				ws.send({
					data:JSON.stringify({
						userid:useuserstore.userlogin.id
					})
				})
			})
			ws.onMessage(msg=>{
				let unit8Arr = new Uint8Array(msg.data) ;
				let encodedString = String.fromCharCode.apply(null, unit8Arr),
				decodedString = decodeURIComponent(escape((encodedString)));
				const aadaya=JSON.parse(decodedString)
				const findata=this.data.find(e=>e.send.id==aadaya.shou&&e.shou.id==aadaya.id)
				findata.shou.speak.push({
					img:aadaya.img,
					spkeak:aadaya.spkeak,
					time:aadaya.time,
					name:aadaya.name,
					type:0
				})
				console.log(findata)
			})
			const rudata=await getunlinedata()
			if(rudata.data.length){
				rudata.data.forEach(e=>{
					const findata=this.data.find(ee=>ee.send.id==e.shou&&ee.shou.id==e.ids)
					console.log(findata,909)
					findata.shou.speak.push({
						img:e.img,
						spkeak:e.spkeak,
						time:e.time,
						name:e.name,
						type:0
					})
				})
			}
		},
	async	mayspeak(data){
			const useuserstore=userstore()
			const findata=this.data.find(e=>e.send.id==data.id&&e.shou.id==data.shou)
			findata.send.speak.push({
				img:useuserstore.userlogin.img,
				spkeak:data.spkeak,
				time:data.time,
				type:1
			})
			return "ok"
		}
		 ,
		addxx(data){
		const rudata=this.data.find(e=>{
				      return e.send.id==data.send&&e.shou.id==data.shou
			})
			if(rudata)return rudata
			this.data.push(
				{
					// {con:"xxx",time:xxx}
					send:{id:data.send,speak:[]},
				    shou:{id:data.shou,speak:[]}
				}
			)
			return this.data.find(e=>{
				      return e.send.id==data.send&&e.shou.id==data.shou
			})
		}
		
	},
	state(){
		return {
			 data:[],
			 wss:""
		}
	},
	getters:{
              shortdata(){
			   const useuserstore=userstore()
			   return (shouid)=>{
				   const rudata=this.data.find(e=>{
				   		      return e.send.id==useuserstore.userlogin.id&&e.shou.id==shouid
				   	})
					return [...rudata.send.speak,...rudata.shou.speak].sort((a,b)=>a.time-b.time)
			   }
		   },
		   shortdatae(){
		   			   const useuserstore=userstore()
		   			   return (shouid)=>{
		   				   const rudata=this.data.find(e=>{
		   				   		      return e.send.id==useuserstore.userlogin.id&&e.shou.id==shouid
		   				   	})
		   					return [...rudata.send.speak,...rudata.shou.speak].sort((a,b)=>b.time-a.time)
		   			   }
		   }
	},
	unistorage:{
		paths:["data"]
	}
})